package edu.dayu.proxyTest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class HWInvocationHandler implements InvocationHandler {
    private Object target;

    private List<Interceptor> list = new ArrayList<>();

    public HWInvocationHandler(Object target, List<Interceptor> list) {
        this.target = target;
        this.list = list;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        for (Interceptor interceptor : list) {
            interceptor.intercept();
        }
        return method.invoke(target,args);
    }

    public static Object wrap(Object target,List<Interceptor> list){
        HWInvocationHandler hwInvocationHandler = new HWInvocationHandler(target, list);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),hwInvocationHandler);
    }
}
